package com.example.cline.controller;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.net.URISyntaxException;
import java.util.Map;

@RestController
public class ChatController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChatController.class);

    private final WebClient webClient;

    public ChatController() throws URISyntaxException {
        this.webClient = WebClient.builder()
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode")
                .build();
    }

    @RequestMapping("/chat/completions")
    public Flux<ServerSentEvent<String>> getChatCompletions(@RequestBody Map<String, Object> paramMap) {
        LOGGER.info("Raw body: {}", JSON.toJSONString(paramMap));
        return webClient.post()
                .uri("/v1/chat/completions")
                .header("Authorization", "Bearer xxxxxx")
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(paramMap) // 根据API要求调整请求体
                .retrieve()
                .bodyToFlux(String.class)
                .map(data -> {
                    LOGGER.info("{}", data);
                    return ServerSentEvent.builder(data).build();
                })
                .onErrorResume(e ->
                        {
                            LOGGER.error("处理失败", e);
                           return  Flux.just(
                                    ServerSentEvent.builder("[ERROR] " + e.getMessage()).build());
                        }
                );
    }
}
